#!/usr/bin/python
import serial, sys, io, os

port0 = sys.argv[1]

ser = serial.Serial()
ser_io = io.TextIOWrapper(io.BufferedRWPair(ser, ser, 1),
                             line_buffering = False)

#initialization and open the port
ser.port = port0
ser.baudrate = 115200
ser.bytesize = serial.EIGHTBITS #number of bits per bytes
ser.parity = serial.PARITY_NONE #set parity check: no parity
ser.stopbits = serial.STOPBITS_ONE #number of stop bits
ser.timeout = 5            #non-block read (1s time out)
ser.writeTimeout = 1     #timeout for write

try:
  ser.open()
except Exception, e:
  print("error opening serial port: %s", str(e))
  exit()

if ser.isOpen():
  try:
    ser.flushInput()  #flush input buffer, discarding all its contents
    ser.flushOutput() #flush output buffer, aborting current output and discard all that is in buffer
  except Exception, e1:
    print("error communicating...: %s", str(e1))
else:
  print("cannot open serial port")

print 'Restoring factory image to app image, wait for 5s and it will oot into factory image'

ser.write('5')
ser.flush()